<template>
  <el-dialog
    :visible.sync="internalVisible"
    title="查看学员记录"
    width="900px"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    append-to-body
    class="training-record-dialog"
  >
    <div v-loading="isLoading" class="dialog-content" ref="staffLogContent">
      <div v-if="trainingDetail">
        <!-- 培训基本信息 -->
        <table class="training-info-table">
          <tr>
            <td class="label">单位名称</td>
            <td colspan="3">{{ trainingDetail.unit_name || '石家庄市政建设集团有限责任公司' }}</td>
          </tr>
          <tr>
            <td class="label">培训名称</td>
            <td colspan="3">{{ trainingDetail.train_name }}</td>
          </tr>
          <tr>
            <td class="label">培训类型</td>
            <td>{{ trainingDetail.train_type_selected_names || '其他类型安全培训' }}</td>
            <td class="label">培训人数</td>
            <td>{{ trainingDetail.train_persons_count || 0 }}</td>
          </tr>
          <tr>
            <td class="label">培训时间</td>
            <td>{{ trainingDetail.train_time || '' }}</td>
            <td class="label">培训学时</td>
            <td>{{ trainingDetail.train_hours || '-' }}</td>
          </tr>
           <tr>
            <td class="label">培训形式</td>
            <td>{{ trainingDetail.train_format || '授课培训' }}</td>
            <td class="label">授课老师</td>
            <td>{{ trainingDetail.teacher || '-' }}</td>
          </tr>
          <tr>
            <td class="label">培训内容</td>
            <td colspan="3" class="training-content-cell">
              <pre>{{ trainingDetail.train_content || trainingDetail.remarks_detail || '-' }}</pre>
            </td>
          </tr>
        </table>

        <!-- 参加培训名单 -->
        <h3 class="table-title">参加培训名单</h3>
        <el-table :data="trainingDetail.participant_list || []" border stripe class="student-list-table">
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" align="center"></el-table-column>
          <el-table-column prop="department_unit" label="组织架构/单位" align="center">
            <template #default="scope">
              <span>{{ scope.row.department_unit || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="exam_score" label="考试成绩" align="center">
            <template #default="scope">
              <span>{{ scope.row.exam_score || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="is_passed" label="是否合格" align="center">
            <template #default="scope">
              <span>{{ scope.row.is_passed || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="!isLoading && !trainingDetail" class="no-data">
        无法加载培训记录详情。
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="downloadArchivePDF" :loading="isDownloadingPDF" icon="el-icon-download"
      >下载PDF</el-button
      >
      <el-button @click="closeDialog">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getTrainDataDetail } from '@/api/manage';
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

export default {
  name: 'TrainingRecordDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    trainingId: {
      type: [String, Number],
      default: null,
    },
    studentListData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      isLoading: false,
      trainingDetail: null,
      internalVisible: false,
      isDownloadingPDF: false,
    };
  },
  watch: {
    visible(newVal) {
      this.internalVisible = newVal;
      if (newVal && this.trainingId) {
        this.fetchTrainingDetails();
      }
      if (!newVal) {
        // Optionally reset detail when dialog is hidden
        this.trainingDetail = null;
      }
    },
    trainingId(newVal, oldVal) {
      if (newVal && this.internalVisible && newVal !== oldVal) {
        this.fetchTrainingDetails();
      }
    },
  },
  methods: {
    closeDialog() {
      this.internalVisible = false;
      this.$emit('update:visible', false); 
      this.$emit('close');
    },
    async fetchTrainingDetails() {
      if (!this.trainingId) {
        this.trainingDetail = null;
        return;
      }
      this.isLoading = true;
      try {
        const response = await getTrainDataDetail({ id: this.trainingId });
        if (response.status === 200 && response.data) {
          // 后端直接返回数据，不是嵌套在 detail 字段中
          this.trainingDetail = response.data;
          console.log('Training details loaded:', this.trainingDetail);
        } else {
          this.trainingDetail = null;
          this.$message.error(response.msg || '获取培训详情失败');
          console.error('Failed to fetch training details:', response);
        }
      } catch (error) {
        this.trainingDetail = null;
        this.$message.error('请求培训详情异常');
        console.error('Error fetching training details:', error);
      } finally {
        this.isLoading = false;
      }
    },
    // formatExamResult method is no longer needed since we're using participant_list from API

    async downloadArchivePDF() {
      if (!this.trainingDetail) {
        this.$message.error('学员记录不存在');
        return;
      }

      this.isDownloadingPDF = true;
      this.$message.info('正在生成PDF，请稍候...');

      try {
        // 获取档案内容DOM元素
        const element = this.$refs.staffLogContent;
        if (!element) {
          this.$message.error('档案内容未加载完成');
          return;
        }

        // 暂时隐藏滚动条，确保完整截图
        const originalOverflow = element.style.overflow;
        element.style.overflow = 'visible';

        // 使用html2canvas将DOM转换为canvas
        const canvas = await html2canvas(element, {
          scale: 2, // 提高清晰度
          useCORS: true, // 允许跨域图片
          allowTaint: true,
          backgroundColor: '#ffffff',
          scrollX: 0,
          scrollY: 0,
          width: element.scrollWidth,
          height: element.scrollHeight,
        });

        // 恢复原始样式
        element.style.overflow = originalOverflow;

        // 创建PDF文档 (A4大小)
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgData = canvas.toDataURL('image/png');

        // 计算图片在PDF中的尺寸
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = pdf.internal.pageSize.getHeight();
        const imgWidth = pdfWidth;
        const imgHeight = (canvas.height * pdfWidth) / canvas.width;

        let position = 0;

        // 如果内容高度超过一页，需要分页
        if (imgHeight > pdfHeight) {
          // 分页处理
          let remainingHeight = imgHeight;

          while (remainingHeight > 0) {
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            remainingHeight -= pdfHeight;
            position -= pdfHeight;

            if (remainingHeight > 0) {
              pdf.addPage();
            }
          }
        } else {
          // 单页处理
          pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
        }

        // 生成文件名
        const today = new Date();
        const dateStr =
          today.getFullYear() +
          String(today.getMonth() + 1).padStart(2, '0') +
          String(today.getDate()).padStart(2, '0');
          const fileName = `学员记录_${dateStr}.pdf`;
          // 下载PDF
          pdf.save(fileName);
          this.$message.success('PDF下载成功');
      } catch (error) {
        console.error('生成PDF错误:', error);
        this.$message.error('生成PDF失败，请稍后重试');
      } finally {
        this.isDownloadingPDF = false;
      }
    },
  },
};
</script>

<style scoped>
.training-record-dialog .el-dialog__body {
  padding: 15px 25px;
}

.dialog-content {
  font-family: 'SimSun', '宋体', sans-serif;
  color: #000;
  padding: 20px;
}

.training-info-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-size: 14px; /* Slightly larger for readability */
  border: 1px solid #000; /* Outer border for the table */
}

.training-info-table td {
  border: 1px solid #000; /* Inner borders for cells */
  padding: 10px;
  line-height: 1.6;
  vertical-align: middle; /* Align content vertically */
}

.training-info-table td.label {
  background-color: #f2f2f2; /* Light grey for labels, similar to image */
  font-weight: bold;
  text-align: center;
  width: 120px; /* Fixed width for label cells */
}

.training-content-cell {
  min-height: 80px; /* Ensure some height for content */
  white-space: pre-wrap; /* Respect newlines and spaces in content */
  vertical-align: top;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 10px;
  text-align: center;
}

.student-list-table {
  width: 100%;
  font-size: 13px;
}

.student-list-table th {
  background-color: #f2f2f2;
  text-align: center;
}

.no-data {
  text-align: center;
  padding: 30px;
  color: #909399;
  font-size: 14px;
}

pre {
  margin: 0;
  font-family: inherit; /* Use the same font as the table */
  white-space: pre-wrap; /* Ensures that the text will wrap and lines will break */
  word-wrap: break-word; /* Allows long words to be broken and wrap onto the next line */
}
</style> 